﻿using Instagram.Version2.Helper;
using Instagram.Version2.Models;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;

// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkID=390556

namespace Instagram.Version2
{
    /// <summary>
    /// An empty page that can be used on its own or navigated to within a Frame.
    /// </summary>
    public sealed partial class PhotoDetails : Page
    {
        private int _photoId;
        private bool _isLike;
        private int _likeId;

        public PhotoDetails()
        {
            this.InitializeComponent();
        }

        /// <summary>
        /// Invoked when this page is about to be displayed in a Frame.
        /// </summary>
        /// <param name="e">Event data that describes how this page was reached.
        /// This parameter is typically used to configure the page.</param>        
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            _photoId = Convert.ToInt32(e.Parameter);
            _isLike = false;

            FillImage();
        }

        async private void Like_Click(object sender, RoutedEventArgs args)
        {
            var like = new LikeModel
                {
                    PhotoID = _photoId,
                    User = GlobalVariables.User
                };
            if (_isLike)
            {
                await ApiCaller.PostAsync("api/Likes/PostLike", like);
            }
            else
            {
                await ApiCaller.DeleteAsync("api/Likes/DeleteLike?ID=" + _likeId);
            }

            FillImage();
        }

        async private void AddComment_Click(object sender, RoutedEventArgs args)
        {
            await ApiCaller.PostAsync("api/Comments/PostComment", new CommentModel
            {
                Text = commentTxt.Text,
                User = GlobalVariables.User,
                PhotoID = _photoId
            });

            commentTxt.Text = "";

            FillImage();
        }

        async private void DeleteComment_Click(object sender, RoutedEventArgs args)
        {
            await ApiCaller.DeleteAsync("api/Comments/DeleteComment?id=" + (sender as Button).Name.Replace("Button", ""));

            FillImage();
        }

        private void Back_Click(object sender, RoutedEventArgs args)
        {
            Frame.GoBack();
        }

        async private void DeletePhoto_Click(object sender, RoutedEventArgs args)
        {
            await ApiCaller.DeleteAsync("api/Photos/DeletePhoto?id=" + _photoId.ToString());

            Frame.GoBack();
        }

        private async void FillImage()
        {
            var photo = await ApiCaller.GetAsync<PhotoDetailModel>("api/Photos/GetPhoto?id=" + _photoId.ToString());

            CheckLikes(photo);

            if (photo.User == GlobalVariables.User)
                deleteBtn.Visibility = Windows.UI.Xaml.Visibility.Visible;
            else
                deleteBtn.Visibility = Windows.UI.Xaml.Visibility.Collapsed;

            title.Text = photo.Title;
            title.FontSize = 20;

            created.Text = photo.Created.ToString();
            created.FontSize = 20;

            likesTxt.FontSize = 20;
            likesTxt.Text = "Likes: " + photo.Likes.Count();

            if (photo.Location != null)
            {
                location.FontSize = 20;
                location.Text = "Location: " + photo.Location;
            }

            imagePreview.Source = Converter.GetImage(photo.Image);
            imagePreview.Name = photo.Id.ToString();

            likeBtn.Content = "Like";
            if (!_isLike)
                likeBtn.Content = "Unlike";

            if (allComments.Children.Count > 0)
            {
                allComments.Children.Clear();
            }

            foreach (var comment in photo.Comments)
            {
                var grid = new Grid();

                grid.Children.Add(new TextBlock()
                {
                    Text = "User: " + comment.User,
                    FontSize = 20,
                    HorizontalAlignment = Windows.UI.Xaml.HorizontalAlignment.Left
                });

                if (photo.User == GlobalVariables.User || comment.User == GlobalVariables.User)
                {

                    var btn = new Button()
                    {
                        Content = "X",
                        HorizontalAlignment = Windows.UI.Xaml.HorizontalAlignment.Right,
                        VerticalAlignment = Windows.UI.Xaml.VerticalAlignment.Top,
                        Name = "Button" + comment.Id.ToString(),
                        FontSize = 10,
                        Width = 40,
                        MinWidth = 40,
                        Height = 40,
                        MinHeight = 40
                    };
                    btn.Click += DeleteComment_Click;

                    grid.Children.Add(btn);
                }

                allComments.Children.Add(grid);

                allComments.Children.Add(new TextBlock()
                {
                    Text = "Comment: " + comment.Text,
                    FontSize = 20
                });
            }
        }

        private void CheckLikes(PhotoDetailModel photo)
        {
            foreach (var like in photo.Likes)
            {
                if (like.User == GlobalVariables.User)
                {
                    _isLike = false;
                    _likeId = like.Id;
                    return;
                }
            }
            _isLike = true;
        }
    }
}
